
import json
import sqlite3
import paho.mqtt.client as mqtt
from setting import *
from db_function import DataBaseFunction
from sentry import TaskSentry

class SubscriptionNsServer:

    def __init__(self, subscription_topic, publish_topic) -> None:

        self.subscription_topic = subscription_topic

        self.publish_topic = publish_topic

    def connect_mqtt(self):

        client = mqtt.Client()

        # 指定回调函数
        client.on_connect = self.on_connect
        client.on_message = self.on_message

        # 建立连接
        client.connect(MQTT_LOCAL_HOST, MQTT_LOCAL_PORT, 60)

        # 发布消息
        client.publish(self.publish_topic ,payload='Hello World',qos=0)

        client.loop_forever()


    def on_connect(self, client, userdata, flags, rc):
        '''连接成功回调'''
        logger.info('Connected with result code '+str(rc))
        client.subscribe(self.subscription_topic)

    def on_message(self, client, userdata, msg):
        '''消息接收回调'''

        parse_msg = json.loads(msg.payload.decode())

        logger.info("receive sensor value：")
        logger.info(parse_msg)

        
        downlink_task_id = parse_msg.get("downlink_task_id")

        if downlink_task_id: # 事务任务回调处理

            with DataBaseFunction() as db:

                db.update_downlink_return_data(json.dumps(parse_msg), dowlink_task_id)

                db.update_downlink_tasks_status(task_id=dowlink_task_id, status=parse_msg["status"])

                return

        text = parse_msg["text"]

        if text == "":

            logger.warning("返回值为空！")
            return

        sn = int(text[2:4], 16)

        sensor_mac = parse_msg["devaddr"]

        logger.info(f"sensor_mac:{sensor_mac}")

        if text.startswith("05"): # 日常数据提交

            data = {
                "type": "senorInfo",

                "data": parse_msg
            }

            logger.info("publish senorInfo:")

            TaskSentry.mqtt_send_data_to_data_center(data)

        else:

            with DataBaseFunction() as db:

                dowlink_task_id = db.select_downlink_task_id_by_status_execute_and_sensor_mac(sensor_mac, sn)

                logger.info(f"dowlink_task_id: {dowlink_task_id}")

                db.update_downlink_return_data(json.dumps(parse_msg), dowlink_task_id)

                status_ = parse_msg.get("status", "success") # 如果没有status健时表示为传感器直接发为的传感器任务可以默认是成功的

                db.update_downlink_tasks_status(task_id=dowlink_task_id, status=status_)


        logger.info("\n\n")
            
if __name__ == "__main__":

    r = SubscriptionNsServer(MQTT_LOCAL_SUBSCRIPTION_TOPIC, MQTT_DATA_CENTER_SUBSCRIPTION_TOPIC)

    r.connect_mqtt()